package cn.monkey.family.server.domain.uc.resource;

import cn.monkey.family.data.crud.repository.ExampleQueryRequestRepository;
import cn.monkey.family.data.crud.repository.QueryRequestRepository;
import cn.monkey.family.data.uc.resource.Resource;
import cn.monkey.family.data.uc.resource.ResourceQueryRequest;
import com.google.common.base.Strings;
import org.springframework.data.domain.*;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.query.ListQueryByExampleExecutor;

import java.util.List;
import java.util.Optional;

@NoRepositoryBean
public interface ResourceRepository extends ExampleQueryRequestRepository<Resource, String, ResourceQueryRequest> {

    @Override
    default Example<Resource> example(ResourceQueryRequest resourceQueryRequest) {
        Resource resource = new Resource();
        ExampleMatcher exampleMatcher = ExampleMatcher.matching();
        String name = resourceQueryRequest.getName();
        if (!Strings.isNullOrEmpty(name)) {
            resource.setName(name);
            exampleMatcher = exampleMatcher.withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        }
        String type = resourceQueryRequest.getType();
        if (!Strings.isNullOrEmpty(type)) {
            resource.setType(type);
            exampleMatcher = exampleMatcher.withMatcher("type", ExampleMatcher.GenericPropertyMatchers.exact());
        }
        String parentId = resourceQueryRequest.getParentId();
        if (!Strings.isNullOrEmpty(parentId)) {
            resource.setParentId(parentId);
            exampleMatcher = exampleMatcher.withMatcher("parentId", ExampleMatcher.GenericPropertyMatchers.exact());
        }
        return Example.of(resource, exampleMatcher);
    }
}
